package com.meta.act.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meta.act.app.system.mapper.TenantBaseMapper;
import com.meta.act.app.tenant.common.FileTypeEnum;
import com.meta.act.app.tenant.entity.TenantUser;
import com.meta.framework.act.entity.SysUser;
import com.meta.act.app.system.repository.TenantBaseRepository;
import com.meta.act.app.system.repository.TenantExtRepository;
import com.meta.act.app.system.repository.TenantFileRepository;
import com.meta.act.app.system.repository.TenantUserRepository;
import com.meta.act.app.service.ISysUserService;
import com.meta.act.app.service.TenantQryService;
import com.meta.act.app.system.repository.TenantBaseRepository;
import com.meta.act.app.tenant.entity.TenantBase;
import com.meta.act.app.tenant.entity.TenantExt;
import com.meta.act.app.tenant.entity.TenantFile;
import com.meta.act.app.tenant.page.Page;
import com.meta.act.app.tenant.req.PageTenantQry;
import com.meta.act.app.tenant.req.TenantDetailQry;
import com.meta.act.app.tenant.req.ro.TenantUserRo;
import com.meta.act.app.tenant.res.TenantDetailIo;
import com.meta.act.app.tenant.res.TenantPageIo;
import com.meta.framework.define.DelFlagEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  租户信息表
 * @Title:      TenantBaseQryServiceImpl
 * @Author:     Simon
 * @Remark:     The modified content
 * @CreateDate: 2020-11-04 15:23:04
 * @Version:    v2.0
 */
@Service
public class TenantQryServiceImpl implements TenantQryService {
	private static final Logger LOGGER = LoggerFactory.getLogger(TenantQryServiceImpl.class);

	@Autowired
	private TenantBaseRepository tenantBaseRepository;

	@Autowired
	private TenantBaseMapper tenantBaseMapper;

	@Autowired
	private TenantExtRepository tenantExtRepository;
	@Autowired
	private TenantFileRepository tenantFileRepository;
	@Autowired
	private TenantUserRepository tenantUserRepository;

	@Autowired
	private ISysUserService userService;

	/**
	 * list tenantBase info
	 * @method      listTenantBase
	 * @param       tenantBase:
	 * @return      List<TenantBase>
	 * @author      Simon
	 * @date        2020-11-04 15:23:04
	 */
	@Override
	public List<TenantPageIo> listTenantBase(TenantBase tenantBase){
		// return tenantBaseRepository.listTenantBase(tenantBase);
		List<TenantBase> list =  tenantBaseRepository.listTenantBase(tenantBase);
		List<TenantPageIo> tenantIoList = new ArrayList<>();
		// 获取查询的所有创建用户信息
		// 批量根据ids获取用户用户信息map
		Map<Long, SysUser> userInfoMap = new HashMap<>();
		if (!CollectionUtils.isEmpty(list)) {
			List<Long> userIds = list.stream().map(v -> v.getCreateUserId()).collect(Collectors.toList());
			if (!org.apache.commons.collections4.CollectionUtils.isEmpty(userIds)) {
				List<SysUser> userInfos = userService.selectUserByIds(userIds);
				if (!CollectionUtils.isEmpty(userInfos)) {
					for (SysUser userInfo : userInfos) {
						userInfoMap.put(userInfo.getUserId(), userInfo);
					}
				}
			}
		}

		for(TenantBase tenant : list){
			TenantPageIo vo = tenant.transform(TenantPageIo.class);
			// 设置创建人姓名
			vo.setCreateUserName("未知");
			if(tenant.getCreateUserId() != null){
				SysUser userInfo = userInfoMap.get(tenant.getCreateUserId());
				if (null != userInfo && null != userInfo.getNickName()) {
					vo.setCreateUserName(userInfo.getNickName());
				}
			}
			tenantIoList.add(vo);
		}
		return tenantIoList;
	}
	@Override
	public List<TenantBase> listTenantUserByUserId(Long userId) {
		TenantUserRo tTenantUser = new TenantUserRo();
		tTenantUser.setUserId(userId);
		return tenantBaseRepository.listTenantByUserId(tTenantUser);
	}
	@Override
	public Page<TenantPageIo> page(PageTenantQry qry) {
		List<TenantPageIo> list = tenantBaseRepository.page(qry);
		Page<TenantPageIo> page = new Page<TenantPageIo>();
		page.setList(list);
		page.setPageNo(qry.getPageNo());
		page.setPageSize(qry.getPageSize());
		page.setTotalRecords(tenantBaseRepository.pageCount(qry));
		return page;
	}

	@Override
	public TenantDetailIo detail(TenantDetailQry qry) {
		TenantBase tenantBase = tenantBaseRepository.getTenantBase(qry.getTenantId());
		if (tenantBase == null){
			return null;
		}
		TenantDetailIo vo = tenantBase.transform(TenantDetailIo.class);
		TenantExt ext = tenantExtRepository.getTenantExt(qry.getTenantId());
		if(ext != null){
			ext.transform(vo);
		}
		//文件
		TenantFile tenantFile = new TenantFile();
		tenantFile.setTenantId(qry.getTenantId());
		tenantFile.setFileType(FileTypeEnum.CREDIT_FILE.getCode());
		vo.setCreditFiles(tenantFileRepository.listTenantFile(tenantFile));
		tenantFile = new TenantFile();
		tenantFile.setTenantId(qry.getTenantId());
		tenantFile.setFileType(FileTypeEnum.TAX_FILE.getCode());
		vo.setTaxFiles(tenantFileRepository.listTenantFile(tenantFile));
		// 人员姓名：从crm租户用户中获取
		SysUser sysUser = new SysUser();
		sysUser.setUserId(tenantBase.getBusinessUserId());
		// sysUser.setTenantId(qry.getTenantId());
		List<SysUser> userList = userService.selectUserList(sysUser);
		if (!CollectionUtils.isEmpty(userList)){
			for (SysUser user : userList) {
				boolean b1 = user.getUserId()!=null;
				boolean b2 = Long.valueOf(user.getUserId()).equals(vo.getLegalPerson());
				if(user.getUserId()!=null && Long.valueOf(user.getUserId()).equals(vo.getLegalPerson())){
					vo.setLegalPersonName(user.getNickName());
				}else if(user.getUserId()!=null && Long.valueOf(user.getUserId()).equals(vo.getBusinessUserId())){
					vo.setBusinessUserName(user.getNickName());
				}
			}
		}
		return vo;
	}

	/**
	 * 获取用户归属的所有租户
	 * @method      listTenantUser
	 * @param       userId:
	 * @return      List<TenantUser>
	 * @author      M.simple
	 * @date        2020/11/25 1:46 下午
	 * @version     v2.0
	 */
	@Override
	public List<TenantUser> listTenant(Long userId){

		TenantUser ro = new TenantUser();
		ro.setUserId(userId);
		return tenantUserRepository.listTenantUser(ro);
	}

	public TenantBase queryTenantBase(TenantDetailQry tenantDetailQry){

		LambdaQueryWrapper<TenantBase> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TenantBase::getTenantId, tenantDetailQry.getTenantId())
				.eq(TenantBase::getDelFlag, DelFlagEnum.O.getCode());

		return this.tenantBaseMapper.selectOne(queryWrapper);
	}

}
